<template>
  <div class="dom-to-image">
    <h2 class="title">DOM转化为图片</h2>
    <div style="display: flex;margin-bottom: 20px;">
      <div class="btn" @click="toImg">点击生成图片</div>
      <div class="btn" @click="clearImage">清空生成图片</div>
    </div>
    <div ref="imgContent" class="image-container">
      <div class="circle"></div>
      <div class="square"></div>
      <div>{{text}}</div>
      <label>
        <input class="input-in-img" type="text" v-model="text" placeholder="可输入文字">
      </label>
      <div>灰色区域可以转成图片</div>
    </div>
    <div class="img-content">
      <img v-for="(img,index) in imgList"
           :key="index"
           :src="img"
           alt="">
    </div>
    <pre v-highlightjs class="code-pre">
      <code class="javascript">
        /**
         * 使用domtoimage可将dom转为图片
         * domtoimage还有其他相关功能
         */
        import domtoimage from 'dom-to-image';
        toImg() {
          domtoimage.toPng(this.$refs.imgContent).then(dataUrl => {
            this.imgList.push(dataUrl)
          }).catch(e => {
            console.error('哎呀，出了点问题!', e);
          })
        }
      </code>
    </pre>
  </div>
</template>

<script>
  import domtoimage from 'dom-to-image';

  export default {
    name: "domToImage",
    data() {
      return {
        imgList: [],
        text: ''
      }
    },
    methods: {
      /**
       * 使用domtoimage可将dom转为图片
       */
      toImg() {
        domtoimage.toPng(this.$refs.imgContent).then(dataUrl => {
          this.imgList.push(dataUrl)
        }).catch(e => {
          console.error('哎呀，出了点问题!', e);
        })
      },
      /**
       * 清空图片
       */
      clearImage() {
        this.imgList = []
      }
    },
  }
</script>

<style scoped>
  .dom-to-image {
    width: 1000px;
  }

  .title {
    margin-bottom: 20px;
  }

  .btn {
    width: 120px;
    height: 30px;
    background-color: dodgerblue;
    color: #fff;
    border-radius: 10px;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
    margin: 0 10px;
  }

  .image-container {
    width: 400px;
    height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-flow: column;
    background-color: #efefef;
  }

  .input-in-img {
    width: 100px;
    height: 20px;
    outline: none;
    line-height: 20;
    margin: 20px;
    padding: 0 10px;
  }

  .circle {
    width: 60px;
    height: 60px;
    margin: 20px;
    border-radius: 100%;
    background-color: #FC9D1D;
  }

  .square {
    width: 60px;
    height: 60px;
    margin: 20px;
    background-color: #0c70fc;
  }

  .img-content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
  }

  .img-content img {
    width: 300px;
  }
</style>
